package com.copa.module.goods.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.copa.domain.ResponseDto;
import com.copa.module.goods.domain.dto.CategoryDto;
import com.copa.module.goods.domain.dto.GoodsDto;
import com.copa.module.goods.domain.entity.CategoryEntity;
import com.copa.module.goods.domain.vo.CategoryAddVo;
import com.copa.module.goods.domain.vo.CategoryListVo;
import com.copa.module.goods.mapper.CategoryDao;
import com.copa.module.goods.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author copa
 * @createDate 2021-01-07 17:03
 * @function
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<CategoryDto> add(CategoryAddVo categoryAddVo) {
        // 添加
        if (categoryAddVo.getId() == null || categoryAddVo.getId() == 0) {
            Boolean insertFlag = categoryDao.insertCategory(categoryAddVo);
            if (insertFlag) {
                return ResponseDto.successMsg("添加类目成功！");
            }
        }
        // 修改
        CategoryEntity categoryEntity = new CategoryEntity();
        BeanUtils.copyProperties(categoryAddVo, categoryEntity);
        int update = categoryDao.updateById(categoryEntity);
        if (update > 0) {
            return ResponseDto.successMsg("修改类目成功！");
        }
        return ResponseDto.errorMsg("系统繁忙，请稍后再操作！");
    }

    @Override
    public ResponseDto<List<CategoryDto>> list() {
        return ResponseDto.success(categoryDao.listCategory());
    }

    @Override
    public ResponseDto<IPage<CategoryDto>> page(CategoryListVo categoryListVo) {
        Page<CategoryDto> page = new Page<>(categoryListVo.getPageVo().getCurrent(), categoryListVo.getPageVo().getSize());
        IPage<CategoryDto> categoryDtoIPage = categoryDao.selectCategoryListPage(page, categoryListVo.getCategoryName());
        if (ObjectUtil.isNotNull(categoryDtoIPage)) {
            return ResponseDto.success(categoryDtoIPage);
        }
        return ResponseDto.errorMsg("抱歉，没查到该类目信息！");
    }
}
